package com.lancoo.cvas.controller;


import cn.hutool.core.collection.CollUtil;
import com.lancoo.cvas.aspect.LogAnnotation;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.mapper.PeriodSchemeMapper;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.response.LockerInfo;
import com.lancoo.cvas.pojo.response.basicPlatform.IdentifyType;
import com.lancoo.cvas.pojo.response.basicPlatform.SubSystemsMainServer;
import com.lancoo.cvas.pojo.response.basicPlatform.TermBasicInfo;
import com.lancoo.cvas.pojo.response.basicPlatform.UserInfo;
import com.lancoo.cvas.pojo.vo.CurrentTermInfo;
import com.lancoo.cvas.service.*;
import com.lancoo.cvas.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "基础平台相关接口")
@RestController
@RequestMapping("/api/v5.0.1/web/yun")
public class YunController {

    @Resource
    private YunService yunService;
    @Resource
    private MajorService majorService;

    @Resource
    private TaskToGradeService taskToGradeService;

    @Resource
    private PeriodSchemeMapper periodSchemeMapper;

    @Resource
    private ClassInfoService classInfoService;


    @Resource
    private PlanTeachingService planTeachingService;

    @Resource
    private TaskInfoService taskInfoService;

    @Resource
    private StudentService studentService;

    @Resource
    private TeacherService teacherService;
    @Resource
    private RoomService roomService;

    @ApiOperation("获取子系统地址")
    @GetMapping("/getSystemUrl")
    public Result<String> getSystemUrl(@ApiParam(value = "系统id，null获取基础平台地址", required = false) @RequestParam(required = false) String sysId) {
        SubSystemsMainServer subSystemsMainServer = yunService.getSubSystemsMainServer(sysId, false);
        return Result.ofSuccess(subSystemsMainServer.getWebSvrAddr());
    }


    @ApiOperation("获取基础平台学校学期")
    @GetMapping("/getTermInfo/{schoolId}")
    public Result<List<TermBasicInfo>> getTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return Result.ofSuccess(yunService.getAllTermInfo(schoolId));
    }


    @ApiOperation("获取当前学期")
    @GetMapping("/getCurrentTermInfo/{schoolId}")
    public Result<CurrentTermInfo> getCurrentTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return Result.ofSuccess(yunService.GetCurrentTermInfo(schoolId));
    }


    @ApiOperation("同步基础平台教室")
    @GetMapping("/syncRoom")
    @LogAnnotation(operationType = "2", operationContent = "同步基础平台教室")
    public Result<String> syncRoom(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                   @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                   @ApiParam(value = "学期", required = true) @RequestParam String term) {

//        List<Room> roomList = roomService.selectRoomList(schoolId,term);
//        if (CollUtil.isEmpty(roomList)) {
        return Result.ofSuccess(yunService.syncRoom(taskId, schoolId, term));
//        } else {
//            return Result.ofSuccess("教室已经同步");
//        }

    }


    @ApiOperation("同步年级专业")
    @GetMapping("/syncMajor")
    public Result<String> syncMajor(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                    @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                    @ApiParam(value = "学期", required = true) @RequestParam String term) {
        if (majorService.lambdaQuery().eq(Major::getTaskId, taskId).count() == 0) {
            yunService.syncMajor(taskId, schoolId, term);
            return Result.ofSuccess("同步专业信息成功");
        } else {
            return Result.ofSuccess("已经同步过专业信息");
        }
    }


    @ApiOperation("同步课时方案")
    @GetMapping("/syncPeriodScheme")
    public Result<String> syncPeriodScheme(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                           @ApiParam(value = "0:小周  1:大周", required = false) @RequestParam(required = false, defaultValue = "0") Integer weekSet,
                                           @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                           @ApiParam(value = "学期", required = true) @RequestParam String term) {
        List<PeriodScheme> list = periodSchemeMapper.getTermPeriodScheme(schoolId, term);
        if (CollUtil.isEmpty(list)) {
            yunService.syncPeriodScheme(taskId, weekSet, schoolId, term);
            return Result.ofSuccess("同步课时方案成功");
        } else {
            return Result.ofSuccess("已经同步过课时方案");
        }
    }


    @ApiOperation("根据token获取用户信息")
    @GetMapping("/getUserDetailInfoByToken")
    public Result<UserInfo> getUserDetailInfoByToken(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token,
                                                     @ApiParam(value = "任务id", required = false) @RequestHeader(required = false) Integer taskId) {
        UserInfo userInfoByToken = yunService.getUserInfoByToken(token, taskId);
        return Result.ofSuccess(userInfoByToken);
    }


    @ApiOperation("同步行政班")
    @GetMapping("/syncClassInfo")
    public Result<String> syncClassInfo(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                        @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                        @ApiParam(value = "学期", required = true) @RequestParam String term) {
        if (classInfoService.lambdaQuery().eq(ClassInfo::getTaskId, taskId).count() == 0) {
            List<String> gradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId)
                    .eq(TaskToGrade::getDeleted, Deleted.NOT.getCode()).list()
                    .stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());
            yunService.syncClassInfo(taskId, schoolId, term, gradeList);
            return Result.ofSuccess("同步行政班成功");
        } else {
            return Result.ofSuccess("已经同步过行政班");
        }
    }


    @ApiOperation("同步基础平台教学计划")
    @GetMapping("/syncPlanTeaching")
    public Result<String> syncPlanTeaching(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                           @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                           @ApiParam(value = "学期", required = true) @RequestParam String term) {
        //数据库教学计划为空时才会执行同步逻辑
        if (planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId).eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()).count() != 0) {
            return Result.ofSuccess("已经同步过教学计划");
        }

        return Result.ofSuccess(yunService.syncPlanTeaching(taskId, schoolId, term));
    }


    @ApiOperation("同步基础平台课程库")
    @GetMapping("/syncCourse")
    public Result<String> syncCourse(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                     @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        return Result.ofSuccess(yunService.syncCourse(taskId, schoolId, taskInfo.getTerm()));
    }

    @ApiOperation("同步基础平台环节库")
    @GetMapping("/syncSegment")
    public Result<String> syncSegment(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                      @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        return Result.ofSuccess(yunService.syncSegment(taskId, schoolId, taskInfo.getTerm()));
    }

    @ApiOperation("同步学生")
    @GetMapping("/syncStudent")
    public Result<String> syncStudent(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                      @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        if (studentService.lambdaQuery().eq(Student::getTaskId, taskId).count() == 0) {
//            List<String> gradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId).list()
//                    .stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());
            yunService.syncStudent(taskId, schoolId);
            return Result.ofSuccess("同步学生信息成功");
        } else {
            return Result.ofSuccess("已经同步过学生信息");
        }
    }

    @ApiOperation("同步教师")
    @GetMapping("/syncTeacher")
    public Result<String> syncTeacher(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                      @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                      @ApiParam(value = "学期", required = true) @RequestParam String term) {

//        List<Teacher> teacherList = teacherService.selectTeacherList(schoolId, term);
//        if (CollUtil.isEmpty(teacherList)) {
            yunService.syncTeacher(taskId, schoolId, term);
            return Result.ofSuccess("同步教师成功");
//        } else {
//            return Result.ofSuccess("已经同步过教师");
//        }
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public Result<UserInfo> getUserInfo(@ApiParam(value = "用户id", required = true) @RequestHeader String userId) {
        return Result.ofSuccess(yunService.getUserInfo(userId));
    }

    @ApiOperation("获取加密锁信息")
    @GetMapping("/getLockInfo")
    public Result<LockerInfo> geLockerInfo(@ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        return Result.ofSuccess(yunService.getSubSystemLockerInfoByID(schoolId));
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    @LogAnnotation(operationType = "19", operationContent = "退出登录")
    public Result<Integer> logout(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token,
                                  @ApiParam(value = "用户id", required = true) @RequestHeader String userId) {
        return Result.ofSuccess(yunService.logout(userId, token));
    }

    @ApiOperation("同步教学班至基础平台")
    @GetMapping("/syncTeachingClassToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步教学班至基础平台")
    public Result syncTeachingClass(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                    @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                    @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                    @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        return yunService.syncTeachingClassToBasic(taskId, userId, userName, schoolId);
    }


    @ApiOperation("同步课表至基础平台-在线选课")
    @GetMapping("/syncOnlineScheduleToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步教学班至基础平台")
    public Result syncOnlineScheduleToBasic(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                            @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                            @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                            @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        return yunService.syncOnlineScheduleToBasic(taskId, userId, userName, schoolId);
    }

    @ApiOperation("同步课表至基础平台")
    @GetMapping("/syncScheduleToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步课表至基础平台")
    public Result syncScheduleToBasic(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                      @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                      @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                      @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        return yunService.syncScheduleToBasic(taskId, userId, userName, schoolId);
    }

    @ApiOperation("根据用户ID获取其身份")
    @GetMapping("/getIdentityTypeByUserID")
    public Result<List<IdentifyType>> getIdentityTypeByUserId(@ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                                              @ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token) {
        return Result.ofSuccess(yunService.getIdentityTypeByUserID(userId, token));
    }


    @ApiOperation("退出登录")
    @GetMapping("/tokenCheck")
    public Object tokenCheck(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token) {
        return Result.ofSuccess(yunService.tokenCheck(token));
    }


}
